import { defineStore } from 'pinia'
import { Toast } from 'vant';
import { getLyric } from '@/request/api/musicApi'

export const PlayStore = defineStore('playliststore', {
  state: () => {
    return {
      // 播放列表
      playList: [
        {
          // 专辑信息
          album: {
            id: 0,
            name: "默认专辑",
            picUrl: "src/assets/images/default_album.jpg",
          },
          // 歌手信息
          artists: [
            {
              id: 0,
              name: '默认歌手'
            }
          ],
          duration: 0,
          musicId: 0,  //音乐ID
          musicName: '默认歌曲名'
        },
      ],

      playListIndex: 0,
      nowPlay: [],
      lyricList: [],
      nowPlayTime: { m: 0, s: 0, ms: 0 }, //当前播放的时间（毫秒）

      searchHistory: [],
    }
  },

  getters: {

  },

  actions: {
    /** 
     * 从歌单点击或者单歌曲时 更新
     * Index  默认0，从第n首开始 index传n
     * 
     * 在MusicPlayer上会监听playList 和 playListIndex  如果改变了就会自动播放
     * */
    updateList(songlist, index = 0) {
      let musicList = [];
      songlist.forEach((item) => {
        // 重构数据
        let data = {
          album: item.al,
          artists: item.ar,
          duration: item.dt / 1000,
          musicId: item.id,  //音乐ID
          musicName: item.name
        }
        musicList.push(data);
      });

      // return Toast('转换成功')
      this.playList = musicList
      this.playListIndex = index;

      this.nowPlay = musicList[index];
      this.getLyricList();
    },

    // 把单曲加到播放列表，播放列表为空时，就为第一首
    storePlaySong(song) {
      // 歌单列表没数据直接播放
      if (this.nowPlay.length == 0) {
        // console.log('播放单曲', typeof (song));
        this.playList = [];
        this.playList.push(song)
        this.playListIndex = 0;
      } else {
        console.log('插入单曲');

        // 如果播放列表有对应ID  直接播放
        let findIndex = '';
        this.playList.forEach((item, index) => {
          if (song.musicId == item.musicId) {
            return findIndex = index
          }
        })
        // 有返回的index的时候
        if (findIndex != '') {
          this.playListIndex = findIndex
        } else {
          this.playList.splice(this.playListIndex + 1, 0, song);
          this.playListIndex += 1;
        }
      }
      // return console.log(this.playList[this.playListIndex]);
      this.nowPlay = this.playList[this.playListIndex];
      this.getLyricList();
    },

    // 从播放列表删除单曲
    sotreDelSong(index) {
      if (index < 0) return Toast.fail('不存在Index');
      let nowIndex = this.playListIndex;

      // 如果删除的正在播放歌曲，则播放下一首
      if (index == nowIndex) {
        this.playList.splice(index, 1);
        this.playListIndex = index;
      } else {
        // 如果小于正在播放的下标，现在的下标自减
        if (index < nowIndex) {
          this.playListIndex--
        }
        this.playList.splice(index, 1);
      }

      this.nowPlay = this.playList[this.playListIndex];
      this.getLyricList();
    },

    // 点击播放列表改变播放的音乐
    sotreChangeSong(index = 0) {
      this.playListIndex = index;

      this.nowPlay = this.playList[index];
      this.getLyricList();
    },

    // 获取歌词
    async getLyricList(id = this.nowPlay.musicId) {
      await getLyric({ id: id }).then(data => {
        let lyric = data.lrc.lyric;
        let arr = lyric.split('\n').map(item => {
          // 有歌词的时候再切割
          let fen = Number(item.slice(1, 3));
          let miao = Number(item.slice(4, 6));
          let haos = Number(item.slice(7, 10));
          let lyrics = item.slice(11);
          let time = parseInt(fen * 60 * 1000 + miao * 1000 + haos);//转为毫秒

          // 判断毫秒是否是数字  如果不是数字 则减一位切割
          if (isNaN(Number(haos))) {
            haos = Number(item.slice(7, 9));
            lyrics = item.slice(10);
            time = Math.floor(fen * 60 * 1000 + miao * 1000 + haos)
          }
          return { fen, miao, haos, lyrics, time }
        })
        this.lyricList = arr.slice(0, -1);
      })
    },

    // 改变搜索历史
    updateSearchHistory(keyword) {
      // 查询是否存在，不存在就添加，存在移动到首位
      if (this.searchHistory.includes(keyword)) {
        let index = this.searchHistory.indexOf(keyword)
        if (index > -1) {
          this.searchHistory.splice(index, 1);
          this.searchHistory.unshift(keyword)
        }
      } else {
        this.searchHistory.unshift(keyword)
      }

      // 超出10个历史，删除最后一个
      if (this.searchHistory.length > 10) this.searchHistory.pop();

    },

    // 改变当前毫秒
    upDateNowPlayTime(time) {
      this.nowPlayTime = time * 1000;
    }
  },


  // 持久化存储
  persist: {
    enabled: true,
    strategies: [
      {
        storage: sessionStorage,
        paths: ['playList', 'playListIndex', 'nowPlay', 'lyricList', 'searchHistory'], //存储的state
      }
    ]
  }
})